import React, { createContext } from 'react';
import { DispatchProp, connect } from 'dva';
import AddPanel from './components/AddPanel';
import { StoreState } from '@/common/store/store';
import ListTable from './components/ListTable';
import FormModal from './components/FormModal';
import { Product } from '@/models/product';
import { PopularRecommend } from './model';

interface ListProps extends DispatchProp {
  recommends: PopularRecommend[];
  products: Product[];
  formTableLoading?: boolean;
  formSubmitLoading?: boolean;
}

interface ListState {
  showModal: boolean;
}

export const ListTableContext = createContext<List>({} as List);

// eslint-disable-next-line react/prefer-stateless-function
export class List extends React.Component<ListProps, ListState> {
  state: ListState = {
    showModal: false,
  };

  onRowRemove(id: number) {
    const { dispatch } = this.props;
    dispatch({
      type: 'popularRecommend/remove',
      payload: id,
    });
  }

  onSwitchChange(record: PopularRecommend) {
    const { dispatch } = this.props;
    dispatch({
      type: 'popularRecommend/update',
      payload: record,
    });
  }

  render() {
    return (
      <div className="row-group">
        <FormModal
          products={this.props.products}
          recommends={this.props.recommends}
          visible={this.state.showModal}
          onCreate={(selectedRows: any) => {
            console.log(selectedRows);
            this.props.dispatch({
              type: 'popularRecommend/addList',
              payload: selectedRows,
              callback: () => {
                this.setState({
                  showModal: false,
                });
              },
            });
          }}
          onCancel={() => {
            this.setState({
              showModal: false,
            });
          }}
          onTableLoading={this.props.formTableLoading}
          onConfirmLoading={this.props.formSubmitLoading}
        />
        <AddPanel
          onButtonClick={() => {
            this.props.dispatch({
              type: 'product/query',
            });
            this.setState({ showModal: true });
          }}
        />
        <ListTableContext.Provider value={this}>
          <ListTable recommends={this.props.recommends} loading={this.props.formSubmitLoading} />
        </ListTableContext.Provider>
      </div>
    );
  }
}

const mapStateToProps = (state: StoreState) => ({
  recommends: state.popularRecommend.recommends,
  products: state.product.products,
  formTableLoading: state.loading.models.product,
  formSubmitLoading: state.loading.models.popularRecommend,
});

export default connect(mapStateToProps)(List);
